package com.cat.admin.controller;

import com.cat.common.annotation.AnonymousAccess;
import com.cat.common.entity.SysUser;
import com.cat.common.entity.UserInfo;
import com.cat.common.model.Result;
import com.cat.common.util.JwtTokenUtil;
import com.cat.common.util.RsaUtils;
import com.cat.common.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dd-cat
 * @version 1.0
 * @date 2020-12-01 16:20
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Api(tags = "系统授权接口")
public class AuthorizationController {

    private final AuthenticationManagerBuilder authenticationManagerBuilder;
    private final JwtTokenUtil jwtTokenUtil;

    @Value("${rsa.private_key}")
    public String privateKey;

    @ApiOperation("登录授权")
    @AnonymousAccess
    @PostMapping("/login")
    public ResponseEntity<Object> login(@Validated @RequestBody SysUser user, HttpServletRequest request) throws Exception {
        // 密码解密
        String password = RsaUtils.decryptByPrivateKey(privateKey, user.getPassword());
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), password);
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 生成令牌
        String token = jwtTokenUtil.generateToken(authentication);
        UserInfo userInfo = (UserInfo) authentication.getPrincipal();

        // 返回 token 与 用户信息
        Map<String, Object> authInfo = new HashMap<String, Object>(2) {{
            put("token", token);
            put("user", userInfo);
        }};
        return ResponseEntity.ok(authInfo);
    }

    @ApiOperation("获取当前用户信息")
    @GetMapping(value = "/info")
    public ResponseEntity<Object> getUserInfo() {
        return ResponseEntity.ok(SecurityUtils.getUser());
    }

    @ApiOperation("退出登录")
    @AnonymousAccess
    @DeleteMapping(value = "/logout")
    public Object logout() {
        return Result.success();
    }
}
